<template>
  <div class="todo-section">
    <h3 class="todo-title">高风险农田待办事项</h3>
    <div class="status-nav">
      <el-button 
        v-for="status in statusOptions" 
        :key="status.value" 
        :type="activeStatus === status.value ? 'primary' : 'default'"
        @click="handleStatusChange(status.value)"
      >
        {{ status.label }}
      </el-button>
    </div>
    
    <div class="todo-list">
      <div class="todo-item" v-for="item in filteredTodos" :key="item.id">
        <div class="todo-header">
          <span class="todo-name">{{ item.farmlandName }}</span>
          <el-tag :type="getRiskTagType(item.risk_level)" size="small">
            风险等级: {{ item.risk_level }}
          </el-tag>
          <el-tag :type="getStatusTagType(item.state)" size="small">
            {{ getStatusLabel(item.state) }}
          </el-tag>
        </div>
        <div class="todo-content">
          <p><strong>处理建议:</strong> {{ item.suggest }}</p>
        </div>
        <div class="todo-actions">
          <el-button 
            v-for="action in availableActions(item.state)" 
            :key="action.status"
            size="small" 
            :type="getButtonType(action.status)"
            @click="changeTodoStatus(item.id, action.status)"
          >
            {{ action.label }}
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { getRiskTodos, updateTodoStatus } from '@/api/risk'
import { getFarmlandName } from '@/api/farmland'
import { ElMessage } from 'element-plus'

// 状态定义
const statusOptions = [
  { value: 0, label: '未开始' },
  { value: 1, label: '进行中' },
  { value: 2, label: '已完成' }
]

const todos = ref([])
const activeStatus = ref(0) // 默认显示未开始

// 处理状态切换
const handleStatusChange = (status) => {
  activeStatus.value = status
  fetchTodos(status) // 根据状态获取待办事项
}

// 获取待办列表（修改后的方法）
const fetchTodos = async (status = null) => {
  try {
    const params = {}
    if (status !== null) {
      params.status = status
    }
    const res = await getRiskTodos(params)
    console.log('API 响应:', res) // 添加日志
    if (res && res.code === 200 && res.data && res.data.length > 0) {
      // 获取农田名称并合并数据
      const todosWithName = await Promise.all(
        res.data[0].map(async item => ({
          ...item,
          farmlandName: await getFarmland(item.farmland_id)
        }))
      )
      todos.value = todosWithName
    } else {
      console.error('响应数据为空或格式不正确:', res)
      ElMessage.error('响应数据为空或格式不正确')
      todos.value = [] // 清空待办事项列表
    }
  } catch (error) {
    console.error('获取待办列表失败:', error)
    ElMessage.error('获取待办列表失败')
    todos.value = [] // 清空待办事项列表
  }
}

async function getFarmland(id) {
  try {
    let res = await getFarmlandName(id)
    if (res && res.data && res.data.length > 0) {
      return res.data[0].farmland_name || `农田ID: ${id}`
    } else {
      console.error('获取农田名称失败:', res)
      return `农田ID: ${id}`
    }
  } catch (error) {
    console.error('获取农田名称失败:', error)
    return `农田ID: ${id}`
  }
}

// 获取状态标签
const getStatusLabel = (status) => {
  return statusOptions.find(opt => opt.value === status)?.label || '未知状态'
}

// 获取风险等级标签类型
const getRiskTagType = (riskLevel) => {
  return riskLevel === '高' ? 'danger' : riskLevel === '中' ? 'warning' : 'success'
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const types = { 0: 'info', 1: 'warning', 2: 'success' }
  return types[status] || ''
}

// 可用的操作按钮
const availableActions = (currentStatus) => {
  const actions = {
    0: [{ status: 1, label: '开始处理' }], // 未开始 -> 开始处理
    1: [
      { status: 0, label: '退回未开始' },
      { status: 2, label: '标记完成' }
    ], // 进行中 -> 退回未开始, 标记完成
    2: [
      { status: 1, label: '重新处理' },
      { status: 0, label: '退回未开始' }
    ] // 已完成 -> 重新处理, 退回未开始
  }
  return actions[currentStatus] || []
}

// 获取按钮类型
const getButtonType = (status) => {
  const types = { 0: 'info', 1: 'warning', 2: 'success' }
  return types[status] || ''
}

// 计算属性：过滤当前状态的待办事项
const filteredTodos = computed(() => {
  if (activeStatus.value === 0) {
    return todos.value.filter(item => item.state === 0);
  } else if (activeStatus.value === 1) {
    return todos.value.filter(item => item.state === 1);
  } else if (activeStatus.value === 2) {
    return todos.value.filter(item => item.state === 2);
  }
  return [];
})

// 更新待办状态
const changeTodoStatus = async (id, newStatus) => {
  try {
    await updateTodoStatus(id, newStatus)
    ElMessage.success('状态更新成功')
    fetchTodos() // 刷新列表
  } catch (error) {
    console.error('更新状态失败:', error)
    ElMessage.error('更新状态失败')
  }
}

// 初始化加载
onMounted(() => {
  fetchTodos()
})
</script>

<style scoped>
.todo-section {
  margin-top: 20px;
}

.todo-title {
  color: #333;
  margin-bottom: 15px;
}

.status-nav {
  margin-bottom: 20px;
}

.status-nav .el-button {
  margin-right: 10px;
}

.todo-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.todo-item {
  background: #fff;
  padding: 15px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.todo-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  gap: 10px;
}

.todo-name {
  font-weight: bold;
  font-size: 16px;
  flex-grow: 1;
}

.todo-content {
  color: #666;
  margin-bottom: 10px;
}

.todo-actions {
  display: flex;
  gap: 10px;
}
</style>